<template>
  <div id="ModeUrl">
    <Breadcrumb content="模式路径" />
    <div class="bodyContent">
      <el-tabs type="border-card">
        <el-tab-pane label="模式路径">
          <Splitpanes class="area">
            <Pane :size="(250 / conWidth) * 100">
              <el-scrollbar>
                <el-tree
                  ref="leftTree"
                  :data="menuList"
                  default-expand-all
                  :props="defaultProps"
                  v-loading="treeLoading"
                  @node-click="handleNodeClick"
                  node-key="id"
                  highlight-current
                  :current-node-key="currentTreeId"
                />
              </el-scrollbar>
            </Pane>
            <Pane :size="(1000 / conWidth) * 100">
              <vxe-toolbar perfect>
                <template #buttons>
                  <vxe-button
                    type="text"
                    class="button-blue"
                    icon="vxe-icon-refresh"
                    content="刷新"
                    :loading="showLoading"
                    @click="getModeUrlList"
                  ></vxe-button>
                  <vxe-button
                    type="text"
                    icon="vxe-icon-delete"
                    class="button-red"
                    content="删除"
                    @click="handleDelete"
                  ></vxe-button>
                </template>
              </vxe-toolbar>
              <div class="leftTable">
                <vxe-table
                  ref="modeUrlTable"
                  border
                  class="mytable-scrollbar"
                  align="center"
                  height="auto"
                  :data="modeUrlList"
                  :loading="showLoading"
                  :row-config="{ isCurrent: true, isHover: true }"
                  :column-config="{ resizable: true }"
                  @current-change="modeUrlClick"
                  show-header-overflow
                  show-overflow
                >
                  <vxe-column type="checkbox" width="40"></vxe-column>
                  <vxe-column type="seq" title="序号" width="40"></vxe-column>
                  <vxe-column field="modeName" title="模式名称"></vxe-column>
                  <vxe-column field="modeUrl" title="模式路径"></vxe-column>
                </vxe-table></div
            ></Pane>
            <Pane :size="(300 / conWidth) * 100">
              <div class="toolbartitle">基本信息</div>
              <el-form
                ref="modeUrlFormRef"
                :model="modeUrlForm"
                label-width="110px"
                class="form-input-m baseForm"
                v-loading="showLoading"
                inline-message
              >
                <el-form-item label="模式名称" prop="modeName">
                  <el-select v-model="modeUrlForm.modeName" class="m-2" placeholder="请选择模式">
                    <el-option
                      v-for="item in modeOptions"
                      :key="item.modeCode"
                      :label="item.modeName"
                      :value="item.modeName"
                    />
                  </el-select>
                  <!-- <el-input v-model="modeUrlForm.modeName" placeholder="模式名称" clearable></el-input> -->
                </el-form-item>
                <el-form-item label="模式路径" prop="modeUrl">
                  <el-input
                    v-model="modeUrlForm.modeUrl"
                    placeholder="请选择模式路径"
                    clearable
                  ></el-input>
                </el-form-item>

                <el-form-item class="form-footer">
                  <template #default>
                    <el-button type="primary" @click="add()">新建</el-button>
                    <el-button type="primary" v-loading="saveLoading" @click="saveModeUrl()"
                      >保存</el-button
                    >
                    <el-button type="default" @click="add()">重置</el-button>
                  </template>
                </el-form-item>
              </el-form></Pane
            >
          </Splitpanes>
        </el-tab-pane>
        <el-tab-pane label="操作日志">
          <LogInfo requestUrl="/sys/modeUrl"></LogInfo>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import LogInfo from '@/components/LogInfo.vue'; //日志

// 接口定义区
interface Tree {
  title: string;
  children?: Tree[];
}
// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let conWidth = ref(document.documentElement.clientWidth); //获取屏幕宽度
let treeLoading = ref(false); //最左侧树加载状态
const menuList: any = reactive([]); //左侧树的数据
const defaultProps = reactive({
  children: 'children',
  label: 'title'
});

// 中间表格数据
let showLoading = ref(false); //中间表格数据加载状态
const modeUrlList: any = reactive([]);
let currentTreeId = ref(''); // 当前树选中行的id
let selectedMenu = reactive({
  id: '',
  label: ''
});

//最右侧基本信息表单
let modeUrlForm = reactive({
  id: '',
  menuId: '',
  modeName: '',
  modeCode: '',
  modeUrl: ''
});
let modeOptions: any = reactive([]);

let saveLoading = ref(false); //最右侧基本信息表单保存按钮

// 方法定义区 =============
onMounted(() => {
  getMenuList();
  getDictItemsList();
});

function formatCommon(arr: any, value: any) {
  for (const item of arr) {
    if (item.modeName == value) {
      return item.modeCode;
    }
  }
}

// 获取字典
async function getDictItemsList() {
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: 'modeUrlDict' } });
  const itemClassType = dictTreeTypeItems.data.find((item: any) => item.code === 'modeUrlDict');
  modeOptions.push(...itemClassType.detailDataList);
  // console.log(modeOptions);
}

// 获取菜单列表
function getMenuList() {
  const url = '/api/sys/getModuleAndMenuList';
  let obj = {
    isReport: '1'
  };
  treeLoading.value = true;
  proxy.$http
    .get(url, { params: obj })
    .then((res: any) => {
      menuList.push(...res.data);
      currentTreeId.value = '';
      selectedMenu.id = '';
      selectedMenu.label = '';
      if (menuList.length > 0) {
        if (menuList[0].children.length != 0) {
          const firstId = menuList[0].children[0].id; //选中的树id
          const selectNodes = menuList[0].children[0]; //选中的树节点
          currentTreeId.value = firstId;
          selectedMenu = selectNodes;
        } else {
          const firstId = menuList[0].id; //树id
          const selectNodes = menuList[0]; //树节点
          currentTreeId.value = firstId;
          selectedMenu = selectNodes;
        }

        proxy.$nextTick(() => {
          proxy.$refs.leftTree.setCurrentKey(currentTreeId.value);
          handleNodeClick(selectedMenu);
        });
      }
      treeLoading.value = false;
    })
    .catch((err: any) => {
      treeLoading.value = false;
      VxeMessage('获取菜单列表异常', VxeNotifyType.error);
    });
}
// 获取模式路径(中间)
function getModeUrlList() {
  modeUrlList.length = 0;
  const url = '/sys/modeUrl/findModeUrlListByMenuId/' + selectedMenu.id;
  showLoading.value = true;
  proxy.$http
    .get(url)
    .then((res: any) => {
      modeUrlList.push(...res.data);
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      VxeMessage('获取模式路径异常', VxeNotifyType.error);
    });
}

// 树点击事件
// function handleNodeClick(data: Tree) {
//   Object.assign(selectedMenu, data);
//   getModeUrlList();// 获取模式路径(中间)
// }

// 树点击事件
function handleNodeClick(data: any) {
  selectedMenu = data;
  getModeUrlList(); // 获取模式路径(中间)
  modeUrlForm.id = '';
  modeUrlForm.menuId = '';
  modeUrlForm.modeName = '';
  modeUrlForm.modeCode = '';
  modeUrlForm.modeUrl = '';
}

// 表格点击事件
function modeUrlClick({ row }: any) {
  Object.assign(modeUrlForm, row);
  modeOptions.length = 0; //清空可选字典
  getDictItemsList();
}

// 删除数据
function handleDelete() {
  const selectRows = (proxy.$refs.modeUrlTable as any).getCheckboxRecords();
  if (selectRows.length > 1) {
    VxeMessage('一次只可选择删除一条数据', VxeNotifyType.warning);
    return;
  } else if (selectRows.length <= 0) {
    VxeMessage('请选择需要删除的用户', VxeNotifyType.warning);
    return;
  } else {
    proxy
      .$confirm('您确定要删除当前选中的这条数据吗?', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const url = '/sys/modeUrl/deleteModeUrl';
        proxy.$http
          .post(url, selectRows[0])
          .then((res: any) => {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            getModeUrlList(); //获取模式路径(中间)
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      });
  }
}

// 添加/重置
function add() {
  Object.keys(modeUrlForm).forEach((key) => {
    modeUrlForm[key] = '';
  });
}

// 保存数据
function saveModeUrl() {
  let url = '';
  if (modeUrlForm.id == '' || modeUrlForm.id == null || modeUrlForm.id == undefined) {
    modeUrlForm.menuId = selectedMenu.id;
    url = '/sys/modeUrl/addModeUrl';
  } else {
    url = '/sys/modeUrl/editModeUrl';
  }
  saveLoading.value = true;
  modeUrlForm.modeCode = formatCommon(modeOptions, modeUrlForm.modeName);
  proxy.$http
    .post(url, modeUrlForm)
    .then((res: any) => {
      VxeMessage(res.status.msg, VxeNotifyType.success);
      saveLoading.value = false;
      getModeUrlList(); //获取模式路径(中间)
      add(); //重置表单
    })
    .catch((err: any) => {
      saveLoading.value = false;
      VxeMessage('保存数据异常', VxeNotifyType.error);
    });
}
</script>
<style lang="scss" scoped>
#ModeUrl {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .el-tabs {
      height: 100%;
      :deep(.el-tabs__content) {
        height: calc(100% - 39px);
        padding: 0;
        .el-tab-pane {
          height: 100%;
          .area {
            background-color: $base-white;
            height: 100%;
            .el-tree {
              padding: 5px;
            }

            // 附加按钮间距
            .button-blue,
            .button-red {
              margin: 5px 0 5px 5px;
            }
            .leftTable {
              height: calc(100% - 39px);
              :deep(.vxe-table--render-wrapper) {
                height: 100%;
                .vxe-table--main-wrapper {
                  height: 100%;
                  .vxe-table--body-wrapper {
                    height: calc(100% - 26px) !important;
                  }
                }
              }
              :deep(.vxe-table--render-default) {
                height: calc(100% - 36px) !important;
              }
            }

            // 右侧基本信息表单
            .baseForm {
              .el-row {
                margin-left: 0 !important;
                margin-right: 0 !important;
              }
              .form-footer {
                :deep(.el-form-item__content) {
                  margin-left: 110px !important;
                }
              }
              .el-form-item--large {
                margin-bottom: 10px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
